package com.gbb.common.tools;

import java.lang.reflect.Field;
import java.util.Iterator;
import java.util.Map;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.StateListDrawable;
import androidx.annotation.DrawableRes;
import androidx.annotation.NonNull;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.Adapter;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.TextView;

import com.gbb.common.log.LogUtils;
import com.gbb.common.utils.DensityUtils;

/**
 *
 */
public class ViewTools {

    /**
     * 获取手机状态栏高度
     *
     * @param context 上下文
     */
    public static int getStatusBarHeight(Context context) {
        Class<?> c = null;
        Object obj = null;
        Field field = null;
        int x = 0, statusBarHeight = 0;
        try {
            c = Class.forName("com.android.internal.R$dimen");
            obj = c.newInstance();
            field = c.getField("status_bar_height");
            x = Integer.parseInt(field.get(obj).toString());
            statusBarHeight = context.getResources().getDimensionPixelSize(x);
        } catch(Exception e1) {
            e1.printStackTrace();
        }
        return statusBarHeight;
    }

    /**
     * View在屏幕上的位置
     *
     * @param view View
     * @return 以屏幕左上角为原点，View左上角的坐标(x,y)：x = location[0]; y = location[1]；
     */
    public static int[] locationOnScreen(View view) {
        int[] location = new int[2];
        view.getLocationOnScreen(location);
        return location;
    }

    /**
     * <pre>
     * 该parent的左上角为原点，View左上角的坐标(view.getX(),view.getY())
     * 以屏幕左上角为原点，View左上角的坐标(x,y)：x = location[0]; y = location[1]；
     * left = marginLeft;
     * top = marginTop;
     * right = marginLeft = getWidth();
     * bottom = marginTop + getHeight();
     * </pre>
     *
     * @param view
     */
    public static void printLocationOfView(View view) {
        int[] location = locationOnScreen(view);
        String format = "【left=%s,top=%s,right=%s,bottom=%s】,【self_x=%s,self_y=%s】,【screen_x=%s,screen_y=%s】";
        String viewInfo = String.format(format,view.getLeft(),view.getTop(),view.getRight(),view.getBottom(),view.getX(),view.getY(),location[0],location[1]);
        LogUtils.i("View Info",viewInfo);
    }

    /**
     * ScrollView嵌套导致进入时页面不在顶部
     *
     * @param view 顶部的第一个VIew
     */
    public static void scrollToTop(View view) {
        //获得焦点，使ScrollView滚动到顶部
        view.setFocusable(true);
        view.setFocusableInTouchMode(true);
        view.requestFocus();
    }

    /**
     * 自动调整ListView高度，解决ScrollView下嵌套ListView导致ListView只显示一条信息的问题
     */
    public static void autoAdjustHeight(ListView mListView) {
        Adapter mAdapter = mListView.getAdapter();
        if(mAdapter == null) {
            return;
        }
        int totalHeight = 0;
        for(int i = 0; i < mAdapter.getCount(); i++) {
            View itemView = mAdapter.getView(i,null,mListView);

            // 妈蛋，不加就空指针
            itemView.setLayoutParams(new ViewGroup.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT));

            // 重新计算item的高宽
            itemView.measure(0,0);

            totalHeight += itemView.getMeasuredHeight();
        }
        ViewGroup.LayoutParams listParams = mListView.getLayoutParams();
        if(listParams == null) {
            listParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT);
        }
        listParams.height = totalHeight + (mListView.getDividerHeight()*(mAdapter.getCount() - 1)) + mListView.getPaddingTop() + mListView.getPaddingBottom();
        mListView.setLayoutParams(listParams);
    }

    /**
     * 自动调整GridView高度
     *
     * @param mGridView
     * @param numColumns 每行多少个
     * @param verticalSpacing 每列之间的间隔，dp
     */
    public static void autoAdjustHeight(GridView mGridView,int numColumns,int verticalSpacing) {
        Adapter mAdapter = mGridView.getAdapter();
        if(mAdapter == null) {
            return;
        }
        int totalHeight = 0;
        int heightCount = mAdapter.getCount()/numColumns;
        heightCount += mAdapter.getCount()%numColumns == 0 ? 0 : 1;
        for(int i = 0; i < heightCount; i++) {
            View itemView = mAdapter.getView(i,null,mGridView);

            // 妈蛋，不加就空指针
            itemView.setLayoutParams(new ViewGroup.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT));

            // 重新计算item的高宽
            itemView.measure(0,0);

            totalHeight += itemView.getMeasuredHeight();
        }
        ViewGroup.LayoutParams listParams = mGridView.getLayoutParams();
        if(listParams == null) {
            listParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT);
        }
        listParams.height = totalHeight + (DensityUtils.dip2px(verticalSpacing)*heightCount) + mGridView.getPaddingTop() + mGridView.getPaddingBottom();
        mGridView.setLayoutParams(listParams);
    }

    /**
     * java代码中实现android背景选择的selector-StateListDrawable的应用
     *
     * @param statusMap Map<int[], Drawable> Key[android.R.attr.state_xxx]
     * @param normal 正常状态的Drawable
     * @return
     */
    public static StateListDrawable createSelectorDrawable(Map<int[], Drawable> statusMap,@NonNull Drawable normal) {
        if(statusMap != null && statusMap.size() > 0) {
            StateListDrawable selectorList = new StateListDrawable();

            // 循环Map取出Key-Value
            for(Map.Entry<int[], Drawable> entry : statusMap.entrySet()) {
                selectorList.addState(entry.getKey(),entry.getValue());
            }
            selectorList.addState(new int[]{},normal);
            return selectorList;
        }
        return null;
    }

    /**
     * java代码中实现android背景选择的selector-StateListDrawable的应用
     *
     * @param mContext
     * @param statusMap Map<int[], Drawable> Key[android.R.attr.state_xxx]
     * @param normal 默认显示的Drawable
     * @return
     */
    public static StateListDrawable createSelectorDrawable(@NonNull Context mContext,Map<int[], Integer> statusMap,@DrawableRes Integer normal) {
        if(statusMap != null && statusMap.size() > 0) {
            Resources res = mContext.getResources();
            StateListDrawable selectorList = new StateListDrawable();

            // 循环Map取出Key-Value
            Iterator<Map.Entry<int[], Integer>> iterator = statusMap.entrySet().iterator();
            while(iterator.hasNext()) {
                Map.Entry<int[], Integer> entry = iterator.next();
                selectorList.addState(entry.getKey(),res.getDrawable(entry.getValue()));
            }
            selectorList.addState(new int[]{},res.getDrawable(normal));
            return selectorList;
        }
        return null;
    }

    /**
     * 获取组件值，去空格
     *
     * @param textView 可传值AutoCompleteTextView、EditText、TextView
     * @return String或者""
     */
    public static String getText(TextView textView) {
        String str = "";
        if(textView != null) {
            str = textView.getText().toString().trim();
        }
        return str;
    }

    /**
     * 截取字符串为XXX...
     *
     * @param str 传入的串
     * @param position 截取的位置
     * @return 截取后字符串
     */
    public static String getSubString(String str,int position) {
        if(str == null || str.length() == 0) {
            return "";
        }
        if(position > 1 && str.length() > position) {
            str = str.substring(0,position - 1) + "...";
        }
        return str;
    }

    /**
     * 获取屏幕尺寸
     *
     * @param mContext 上下文
     * @return [宽,高]
     */
    public static int[] getScreenSize(Context mContext) {
        WindowManager wm = (WindowManager)mContext.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);
        return new int[]{outMetrics.widthPixels,outMetrics.heightPixels};
    }

    /***
     * 获取屏幕宽度px
     * @param mContext 上下文
     * @return 屏幕宽px
     */
    public static int getScreenWith(Context mContext) {
        WindowManager wm = (WindowManager)mContext.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);
        return outMetrics.widthPixels;
    }

    /***
     * 获取屏幕高度px
     * @param mContext 上下文
     * @return 屏幕宽px
     */
    public static int getScreenHeight(Context mContext) {
        WindowManager wm = (WindowManager)mContext.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);
        return outMetrics.heightPixels;
    }

    /**
     * 当前设备资源文件夹
     *
     * @param densityDpi 密度值
     */
    public static String getResourceFolder(int densityDpi) {
        switch(densityDpi) {
            case 120:
                return "ldpi";
            case 160:
                return "mdpi";
            case 240:
                return "hdpi";
            case 320:
                return "xhdpi";
            case 480:
                return "xxhdpi";
            default:
                return "unknown";
        }
    }


}
